package com.example.second.controller;

import com.alibaba.fastjson.JSON;
import com.example.second.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.hash.HashMapper;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@CrossOrigin
@RestController
public class UserController {

    @Autowired
    private IUserService iUserService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private final String SALT = "sec";

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Map<String,Object> login(String username, String password, String yzcode,String realyzcode,HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){

        //验证码校验
        if (yzcode.length()<4||!yzcode.equals(realyzcode)){
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("result", false);
            resultMap.put("msg", "验证码错误");
            return resultMap;
        }

        String passwordmd5 = DigestUtils.md5DigestAsHex((password + "/" + SALT).getBytes());
        Map<String,Object> userMap = iUserService.getUser(username, passwordmd5);
        if(userMap.get("msg")=="密码错误"){
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("result", false);
            resultMap.put("msg", "密码错误");
            return resultMap;
        }else if((Boolean) userMap.get("result")==false){
            return userMap;
        }


        //查一下有没有session,如果没有，新建一个session
        String user_id = "";
        if (httpServletRequest.getCookies()!=null){
            for( Cookie cookie:httpServletRequest.getCookies()){

                String sessionid = cookie.getValue();
                String session = stringRedisTemplate.opsForValue().get(sessionid);
                if(session==null){
                    continue;
                }
                Map<String,Object> usermap = JSON.parseObject(stringRedisTemplate.opsForValue().get(sessionid), Map.class);

                if(!usermap.isEmpty()&&usermap.get("user_id")!=null){
                    user_id = usermap.get("user_id").toString();
                    break;
                }
            }
        }

        if(user_id.equals("")){
            String uuid = UUID.randomUUID().toString();
            Cookie cookie = new Cookie(username,uuid );
            cookie.setDomain("localhost");
            cookie.setPath("/");
            httpServletResponse.addCookie(cookie);
            stringRedisTemplate.opsForValue().set(uuid, JSON.toJSONString(userMap), 3600, TimeUnit.SECONDS);
        }
        return userMap;
    }

    @RequestMapping(value = "/adminlogin",method = RequestMethod.POST)
    public Map<String,Object> adminlogin(String username, String password, String yzcode,String realyzcode,HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){

        //验证码校验
        if (yzcode.length()<4||!yzcode.equals(realyzcode)){
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("result", false);
            resultMap.put("msg", "验证码错误");
            return resultMap;
        }

        String passwordmd5 = DigestUtils.md5DigestAsHex((password + "/" + SALT).getBytes());
        Map<String,Object> userMap = iUserService.getAdminUser(username, passwordmd5);

        if(userMap.get("msg")=="密码错误"){
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("result", false);
            resultMap.put("msg", "用户名或密码错误");
            return resultMap;
        }else if((Boolean) userMap.get("result")==false){
            return userMap;
        }

        //查一下有没有session,如果没有，新建一个session
        String user_id = "";
        if (httpServletRequest.getCookies()!=null){
            for( Cookie cookie:httpServletRequest.getCookies()){

                String sessionid = cookie.getValue();
                String session = stringRedisTemplate.opsForValue().get(sessionid);
                if(session==null){
                    continue;
                }
                Map<String,Object> usermap = JSON.parseObject(stringRedisTemplate.opsForValue().get(sessionid), Map.class);

                if(usermap!=null&&usermap.get("user_id")!=null&&usermap.get("user_role")!=null&&usermap.get("user_role").equals("1")){
                    user_id = usermap.get("user_id").toString();
                    break;
                }
            }
        }

        if(user_id.equals("")){

            String uuid = UUID.randomUUID().toString();
            Cookie cookie = new Cookie(username,uuid );

            cookie.setDomain("localhost");
            cookie.setPath("/");
            httpServletResponse.addCookie(cookie);
            userMap.put("user_role", "1");

            stringRedisTemplate.opsForValue().set(uuid, JSON.toJSONString(userMap), 3600, TimeUnit.SECONDS);
        }
        return userMap;
    }


}
